package com.reebake.ideal.response.wrapper.core;

import com.reebake.ideal.exception.BaseException;
import com.reebake.ideal.response.wrapper.properties.ResponseBodyWrapperProperties;
import com.reebake.ideal.servlet.core.ResponseBodyWrapper;
import com.reebake.ideal.servlet.util.WebUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

public class DefaultResponseBodyWrapper implements ResponseBodyWrapper {
    @Autowired
    private ResponseBodyWrapperProperties responseBodyWrapperProperties;

    @Override
    public Object convert(Integer code, Object object) {
        Map<String, Object> body = new HashMap<>();

        if(object instanceof Exception exception) {
            String message = exception.getLocalizedMessage();
            body.put(responseBodyWrapperProperties.getMessageParameterName(), message);
            if(code == null) {
                if (object instanceof BaseException baseException) {
                    code = baseException.getCode();
                }
            }
            if(code == null) {
                code = 500;
            }
            body.put(responseBodyWrapperProperties.getCodeParameterName(), code);
        }else {
            body.put(responseBodyWrapperProperties.getDataParameterName(), object);
            body.put(responseBodyWrapperProperties.getMessageParameterName(), responseBodyWrapperProperties.getSuccessMessage());
            body.put(responseBodyWrapperProperties.getCodeParameterName(), responseBodyWrapperProperties.getSuccessCode());
        }

        return body;
    }

    @Override
    public void write(HttpServletResponse response, Object object) {
        WebUtil.writeJson(response, object);
    }
}
